var express = require('express');
var router = express.Router();

var { sqlQuery } = require("../tool/conn");

/* GET home page. */
// /goods/
router.get('/', function (req, res, next) {
    res.end("/goods");
});


// /goods/searchAllGoods   -> 查询所有商品  -> 无需接收参数
router.get('/searchAllGoods', function (req, res, next) {

    var sql = "select id,name,img,price from goodslist";
    sqlQuery(sql).then(list => {
        res.json({
            status: true,
            message: "OK",
            list
        })
    }).catch(err => {
        res.json({
            status: false,
            ...err,
        })
    })


});

// /goods/searchGoodsOrderLimit  商品查询 排序 分页

// 接收前端传递的参数  wd col type page size 

// 开发流程
// 1. 立项(确定项目主题,功能)
// 2. 将需求整理为需求文档
// 3. UI绘制原型图    后端接口搭建(接口文档 -> 后端要什么前端就传什么)
// 4. 前端对接UI还原设计图  对接后端前后端交互
// 5. 测试 -> bug文档 
// 6. 上线 -> 线上测试
// 7. 项目推广  项目维护/更新


router.get('/searchGoodsOrderLimit', function (req, res, next) {
    
    var { wd = "", col = "id", type = "asc", page = 1, size = 10 } = req.query;
    var colList = ["id","name","price"];
    if(!colList.includes(col)){
        res.json({
            status:false,
            message:"只能根据id,name,price三者排序"
        })
    }
    var typeList = ["asc","desc"]
    if(!typeList.includes(type)){
        res.json({
            status:false,
            message:"只能升序(asc)和降序(desc)",
        })
    }
    if(size<1 || size >100 || size %1 !=0){
        res.json({
            status:false,
            message:"查询数据只能是1-100的整数",
        })
    }

    // 页码限制
    // 最小值: 1 
    // 最大值: 查询的数据的总数量 / size -> 向上取值

    // 查询的数据的总数量? 怎么求 

    var searchSql = `select id,name,img,price from goodslist where name like '%${wd}%'`;


    sqlQuery(searchSql).then(searchList=>{
        var maxPage = Math.floor(searchList.length / size);

        // 限制页码在有效范围内
        if(page > maxPage){
            page = maxPage;
        }
        if(page < 1){
            page = 1;
        }

        var sql = `select id,name,img,price from goodslist where name like '%${wd}%' order by ${col} ${type} limit ${(page - 1) * size},${size}`;

        sqlQuery(sql).then(list => {
            res.json({
                status: true,
                total:searchList.length,
                maxPage: maxPage,
                current:page,
                message: "OK",
                list,
            })
        }).catch(err => {
            res.json({
                status: false,
                ...err,
            })
        })


    }).catch(err=>{
        
    })



});


module.exports = router;
